<template>
  <div class="h-full">
    <BasicTable @register="registerVersionTable" v-if="getHasRepository">
      <template #toolbar>
        <a-button type="primary" @click="() => openAddEntityVersionModal()">创建实体版本</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :stopButtonPropagation="true"
            :actions="[
              {
                icon: ICON.RESTORE,
                tooltip: {
                  title: '还原版本',
                  placement: 'top',
                },
                onClick: openRestoreModal.bind(null, true, { record }),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <SettingWarehouse v-else />
    <AddEntityVersionModal @register="registerAddModal" @success="handleSuccess" />
    <RestoreVersionModal @register="registerRestoreModal" @success="handleSuccess" />
  </div>
</template>

<script setup lang="ts">
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { versionControlTableSchema, searchSchema } from './versionControl.data';
  import AddEntityVersionModal from './components/AddEntityVersionModal.vue';
  import RestoreVersionModal from './components/RestoreVersionModal.vue';
  import { ICON } from '/@/enums/iconEnum';
  import { useModal } from '/@/components/Modal';
  import SettingWarehouse from '../SettingWarehouse.vue';
  import { onMounted } from 'vue';
  import {
    versionTable,
    createEntityVersion,
    getVersionCreateRequestStatus,
    restoreVersion,
    getRestoreVersionStatus,
    entityVersionTable,
  } from '/@/api/thingsborad/advanced/versionControl/versionControl';
  import {
    versionTableListDataItem,
    versionTableParams,
    versionTableCreateParams,
    versionTableRollbackParams,
  } from '/@/api/thingsborad/advanced/versionControl/versionControlModel';
  import { computed } from 'vue';
  import {
    tableFormStyleSetting,
    publicDrawerTableFormStyleSetting,
    tableStyleSetting,
  } from '/@/settings/thingsBoardDesign';
  import { useSystemStoreWithOut } from '/@/store/modules/thingsboard/systemParams';

  const props = defineProps({
    isComponent: {
      type: Boolean,
      default: false,
    },
    entityType: {
      type: String,
    },
    entityId: {
      type: String,
    },
  });
  const userStore = useSystemStoreWithOut();
  const getHasRepository = computed(() => userStore.hasRepository);

  const [registerVersionTable, { setProps, reload }] = useTable({
    title: '版本',
    columns: versionControlTableSchema,
    ...tableStyleSetting,
    pagination: true,
    afterFetch: (res) => {
      let list: versionTableListDataItem[] = [];
      res.length != 0
        ? res.forEach((item: any) => {
            let tableItem: versionTableListDataItem = {
              timestamp: item.timestamp,
              id: item.id,
              name: item.name,
              author: item.author,
            };
            list.push(tableItem);
          })
        : null;
      return list;
    },
    fetchSetting: {
      pageField: 'page',
      sizeField: 'pageSize',
      listField: 'data',
      totalField: 'totalElements',
    },
  });
  const [registerAddModal, { openModal, setModalProps, closeModal }] = useModal();
  const [registerRestoreModal, { openModal: openRestoreModal }] = useModal();
  const openAddEntityVersionModal = () => openModal(true);

  const handleSuccess = async ({ key, versionId, values, collapseFormValues }) => {
    if (key == 'add') {
      setModalProps({ loading: true });
      let params: versionTableCreateParams = {
        branch: values.branch,
        entityTypes: collapseFormValues.collapseFormValues,
        syncStrategy: values.syncStrategy,
        versionName: values.versionName,
        type: 'COMPLEX',
      };
      const requestId = await createEntityVersion(params);
      const interval = setInterval(async () => {
        const value = await getVersionCreateRequestStatus(requestId);
        if (value.done) {
          clearInterval(interval);
          setModalProps({ loading: false });
          closeModal();
        }
      }, 2000);
    } else if (key == 'restore') {
      setModalProps({ loading: true });
      let params: versionTableRollbackParams = {
        entityTypes: collapseFormValues.collapseFormValues,
        type: 'ENTITY_TYPE',
        versionId: versionId,
      };
      const requestId = await restoreVersion(params);
      const interval = setInterval(async () => {
        const value = await getRestoreVersionStatus(requestId);
        if (value.done) {
          clearInterval(interval);
          setModalProps({ loading: false });
          closeModal();
        }
      }, 2000);
    }
  };

  onMounted(async () => {
    if (getHasRepository.value) {
      if (props.isComponent) {
        setProps({
          formConfig: {
            layout: 'horizontal',
            schemas: searchSchema,
            showAdvancedButton: false,
            ...publicDrawerTableFormStyleSetting,
            actionColOptions: {
              md: { span: 12, offset: 12 },
              lg: { span: 8, offset: 0 },
              xl: { span: 6, offset: 6 },
              xxl: { span: 6, offset: 6 },
            },
          },
          api: entityVersionTable,
          beforeFetch: (val) => {
            let params: any = {
              pagination: {
                page: val.page - 1,
                pageSize: val.pageSize,
                sortOrder: val.order == 'ascend' ? 'ASC' : 'DESC',
                sortProperty: 'timestamp',
                branch: val.branch ? val.branch : 'main',
              },
              entityType: props.entityType,
              entityId: props.entityId,
            };
            val?.textSearch ? (params.pagination.textSearch = val.textSearch) : null;
            return params;
          },
        });
        reload();
      } else {
        setProps({
          formConfig: {
            layout: 'horizontal',
            schemas: searchSchema,
            showAdvancedButton: false,
            ...tableFormStyleSetting,
            actionColOptions: {
              md: { span: 8, offset: 0 },
              lg: { span: 6, offset: 6 },
              xl: { span: 4, offset: 12 },
              xxl: { span: 4, offset: 12 },
            },
          },
          api: versionTable,
          beforeFetch: (val) => {
            let params: versionTableParams = {
              page: val.page - 1,
              pageSize: val.pageSize,
              sortOrder: val.order == 'ascend' ? 'ASC' : 'DESC',
              sortProperty: 'timestamp',
              branch: val.branch ? val.branch : 'main',
            };
            val?.textSearch ? (params.textSearch = val.textSearch) : null;
            return params;
          },
        });
        reload();
      }
    }
  });
</script>
